package com.forsir.android.mhfinance;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.forsir.android.mhfinance.helper.CalculatorSolver;
import com.forsir.android.mhfinance.helper.DbAdapter;
import com.forsir.android.mhfinance.storeObjects.AccountsList;
import com.forsir.android.mhfinance.storeObjects.CategoryList;
import com.forsir.android.mhfinance.storeObjects.Payment;
import com.forsir.android.mhfinance.storeObjects.PaymentList;
import com.forsir.android.mhfinance.storeObjects.Repeating;
import com.forsir.android.mhfinance.storeObjects.RepeatingList;

public class SetAmount extends Activity {
	public static final String REQUEST_ACCOUNT_ID = "account_id";
	public static final String REQUEST_CATEGORY_ID = "category_id";
	public static final String REQUEST_PAYMENT_ID = "payment_id";
	public static final String REQUEST_TRANSFER = "transfer";
	public static final String RETURN_SHOW_REPORT = "show_report";
	public static final String REQUEST_REPEATING = "repeating";

	public static final int REPEATING_TYPE_NONE = 0;
	public static final int REPEATING_TYPE_REPEATING = 1;
	public static final int REPEATING_TYPE_NO_REPEATING = 2;

	private final static String TAG = "MHFinance";
	private final static int DATE_PICKER_DIALOG = 1;
	private final static int TIME_PICKER_DIALOG = 2;
	private final static int TYPE_MORE_DIALOG = 3;
	private final static int REPEATING_TYPE_DIALOG = 4;
	private final static int REPEATING_END_DATE_PICKER_DIALOG = 5;
	private final static int REMAINDER_INFO_DIALOG = 6;

	private final static int CALCULATOR_ACTIVITY = 100;
	private final static int SELECT_CATEGORY_ACTIVITY = 101;
	private final static int SELECT_ACCOUNT_ACTIVITY = 102;
	private final static int SELECT_TRANSFER_ACCOUNT_ACTIVITY = 103;
	// private final static int NEW_PAYMENT_ACTIVITY = 104;

	private String[] typeString = new String[] {};
	private String[] repeatingTypeString = new String[] {};

	private final Payment actualPayment = new Payment(-1);
	private Payment lastPayment = null;
	private Button accountButton;
	private Button categoryButton;
	private Button dateButton;
	private Button timeButton;
	private Button typeButton;
	private Button typeMoreButton;
	private TextView accountText;
	private TextView categoryText;
	private TextView descriptionText;
	private TextView amountText;
	private TextView currencyBeforeText;
	private TextView currencyAfterText;
	private TextView transferText;
	private Button transferAccountButton;
	private Button saveButton;
	private Button cancelButton;
	private Button saveAndNextButton;
	private ImageButton calcButton;
	private Button repeatingTypeButton;
	private Button repeatingEndTimeButton;
	private Button repeatingSetButton;
	private Button repeatingPlusButton;
	private Button repeatingMinusButton;
	private TextView repeatingOccurences;
	private LinearLayout repeatingLayout;
	private LinearLayout repeatingSecondLayout;

	private int editRepeating = REPEATING_TYPE_NONE;
	private Resources resource;
	private DbAdapter mDbHelper;
	private SharedPreferences mPreferenceSettings;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.set_amount);

		mDbHelper = new DbAdapter(this, this);
		mDbHelper.open();
		mPreferenceSettings = PreferenceManager.getDefaultSharedPreferences(this);

		typeString = new String[] { getString(R.string.type_withdraw), getString(R.string.type_deposit), getString(R.string.type_remainder),
		        getString(R.string.type_transfer_from), getString(R.string.type_transfer_to) };
		repeatingTypeString = new String[] { getString(R.string.repeating_none), getString(R.string.repeating_daily), getString(R.string.repeating_weekly),
		        getString(R.string.repeating_monthly), getString(R.string.repeating_monthly_day), getString(R.string.repeating_quarter_yearly),
		        getString(R.string.repeating_yearly) };

		resource = getResources();

		setButtonElements();

		final Bundle extras = getIntent().getExtras();
		if (extras != null) {
			if (extras.getBoolean(SetAmount.REQUEST_TRANSFER, false)) {
				actualPayment.setType(Payment.TYPE_TRANSFER_FROM);
			}
			editRepeating = extras.getInt(SetAmount.REQUEST_REPEATING, REPEATING_TYPE_NONE);
			actualPayment.setAccountById(extras.getLong(SetAmount.REQUEST_ACCOUNT_ID, -1));
			actualPayment.setSubcategoryById(extras.getLong(SetAmount.REQUEST_CATEGORY_ID, -1));
			actualPayment.setId(extras.getLong(SetAmount.REQUEST_PAYMENT_ID, -1));
			actualPayment.loadFromDb(mDbHelper);
			if (actualPayment.getRepeating().getType() != Repeating.TYPE_NONE) {
				lastPayment = new Payment();
				lastPayment.copyPayment(actualPayment);
				lastPayment.setRepeating(new Repeating());
				lastPayment.getRepeating().copyRepeating(actualPayment.getRepeating());
			}
		}

		if (savedInstanceState != null) {
			editRepeating = savedInstanceState.getInt(SetAmount.REQUEST_REPEATING, REPEATING_TYPE_NONE);
			actualPayment.fillFromBundle(savedInstanceState);
			actualPayment.getRepeating().fillFromBundle(savedInstanceState);
		}

		if (actualPayment.getAccount() == null) {
			actualPayment.setAccount(AccountsList.getFirst());
		}

		if (editRepeating == REPEATING_TYPE_REPEATING) {
			// set date as first date of repeating
			actualPayment.setDate(actualPayment.getRepeating().getBeginDate(mDbHelper));
			actualPayment.getRepeating().computeOccurrences(actualPayment.getDate());
		}

		fillForm();

		descriptionText.setText(actualPayment.getDescription());
		if (actualPayment.getAmount() == 0) {
			amountText.setText("");
		} else {
			amountText.setText(actualPayment.getAmountString());
		}

		// set listeners
		typeButton.setOnClickListener(typeButtonClickListener);
		typeMoreButton.setOnClickListener(typeMoreButtonClickListener);
		dateButton.setOnClickListener(dateButtonListener);
		dateButton.setOnLongClickListener(dateButtonLongClickListener);
		timeButton.setOnClickListener(timeButtonListener);
		timeButton.setOnLongClickListener(timeButtonLongClickListener);
		accountButton.setOnClickListener(accountButtonListener);
		transferAccountButton.setOnClickListener(transferaccountButtonListener);
		categoryButton.setOnClickListener(categoryButtonListener);
		calcButton.setOnClickListener(calcButtonListener);

		repeatingTypeButton.setOnClickListener(repeaterTypeButtonListener);
		repeatingEndTimeButton.setOnClickListener(repeaterEndDateButtonListener);
		repeatingPlusButton.setOnClickListener(repeaterPlusButtonListener);
		repeatingPlusButton.setOnLongClickListener(repeaterPlusButtonLongListener);
		repeatingMinusButton.setOnClickListener(repeaterMinusButtonListener);
		repeatingMinusButton.setOnLongClickListener(repeaterMinusButtonLongListener);
		repeatingSetButton.setOnClickListener(repeaterSetButtonListener);

		cancelButton.setOnClickListener(cancelListener);
		saveButton.setOnClickListener(saveAndReportListener);
		saveAndNextButton.setOnClickListener(saveAndNewListener);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		Builder builder = null;

		switch (id) {
			case DATE_PICKER_DIALOG:
				dialog = new DatePickerDialog(this, dateSetListener, actualPayment.getYear(), actualPayment.getMonth(), actualPayment.getDay());
				break;
			case REPEATING_END_DATE_PICKER_DIALOG:
				dialog = new DatePickerDialog(this, repeatEndDateSetListener, actualPayment.getRepeating().getEndYear(), actualPayment.getRepeating().getEndMonth(),
				        actualPayment.getRepeating().getEndDay());
				break;
			case TIME_PICKER_DIALOG:
				final boolean is24HourView = !getString(R.string.format_time).endsWith("a");
				dialog = new TimePickerDialog(this, timeSetListener, actualPayment.getHour(), actualPayment.getMinute(), is24HourView);
				break;
			case REPEATING_TYPE_DIALOG:
				builder = new AlertDialog.Builder(this);
				builder.setTitle(R.string.select_repeating_type);

				builder.setItems(repeatingTypeString, repeatingTypeSelectButtonListener);

				dialog = builder.create();
				break;
			case TYPE_MORE_DIALOG:
				builder = new AlertDialog.Builder(this);
				builder.setTitle(R.string.select_type);

				builder.setItems(typeString, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialogInterface, int which) {
						switch (which) {
							case 0:
								actualPayment.setType(Payment.TYPE_WITHDRAW);
								break;
							case 1:
								actualPayment.setType(Payment.TYPE_DEPOSIT);
								break;
							case 2:
								actualPayment.setType(Payment.TYPE_REMAINDER);
								break;
							case 3:
								actualPayment.setType(Payment.TYPE_TRANSFER_FROM);
								break;
							case 4:
								actualPayment.setType(Payment.TYPE_TRANSFER_TO);
								break;
						}
						fillForm();
						if (actualPayment.getType() == Payment.TYPE_REMAINDER) {
							if (mPreferenceSettings.getBoolean(getString(R.string.key_remainder_info), false)) {
								showDialog(REMAINDER_INFO_DIALOG);
							}
						}
					}
				});

				dialog = builder.create();
				break;
			case REMAINDER_INFO_DIALOG:
				builder = new AlertDialog.Builder(this);
				builder.setTitle(R.string.remainder_info);
				builder.setMessage(R.string.remainder_info_text);
				builder.setPositiveButton(R.string.dont_show_again, remainderInfoClickListener);
				builder.setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				});

				dialog = builder.create();
				break;
		}

		return dialog;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
			case DATE_PICKER_DIALOG:
				((DatePickerDialog) dialog).updateDate(actualPayment.getYear(), actualPayment.getMonth(), actualPayment.getDay());
				break;
			case REPEATING_END_DATE_PICKER_DIALOG:
				((DatePickerDialog) dialog).updateDate(actualPayment.getRepeating().getEndYear(), actualPayment.getRepeating().getEndMonth(), actualPayment
				        .getRepeating().getEndDay());
				break;
			case TIME_PICKER_DIALOG:
				((TimePickerDialog) dialog).updateTime(actualPayment.getHour(), actualPayment.getMinute());
				break;
		}
	}

	// the callback received when the user "sets" the date in the dialog
	private final OnDateSetListener dateSetListener = new OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			Log.d(TAG, "Date Go to:" + year + "/" + monthOfYear + "/" + dayOfMonth);
			actualPayment.setDate(year, monthOfYear, dayOfMonth);
			actualPayment.getRepeating().setOccurrences(actualPayment.getRepeating().getOccurrences(), actualPayment.getDate());
			fillForm();
		}
	};

	// the callback received when the user "sets" the date in the dialog
	private final OnDateSetListener repeatEndDateSetListener = new OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			actualPayment.getRepeating().setEndDate(year, monthOfYear, dayOfMonth);
			actualPayment.getRepeating().computeOccurrences(actualPayment.getDate());
			fillForm();
		}
	};

	// the callback received when the user "sets" the date in the dialog
	private final OnTimeSetListener timeSetListener = new OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			Log.d(TAG, "Time Go to:" + hourOfDay + ":" + minute);
			actualPayment.setTime(hourOfDay, minute);
			fillForm();
		}
	};

	private void setButtonElements() {
		accountButton = (Button) findViewById(R.id.set_amount_account);
		accountText = (TextView) findViewById(R.id.set_amount_account_text);
		categoryButton = (Button) findViewById(R.id.set_amount_category);
		categoryText = (TextView) findViewById(R.id.set_amount_category_text);
		dateButton = (Button) findViewById(R.id.set_amount_date);
		timeButton = (Button) findViewById(R.id.set_amount_time);
		typeButton = (Button) findViewById(R.id.set_amount_type);
		typeMoreButton = (Button) findViewById(R.id.set_amount_type_more);
		amountText = (TextView) findViewById(R.id.set_amount_amount);
		descriptionText = (TextView) findViewById(R.id.set_amount_description);
		currencyBeforeText = (TextView) findViewById(R.id.set_amount_currency_before);
		currencyAfterText = (TextView) findViewById(R.id.set_amount_currency_after);
		saveButton = (Button) findViewById(R.id.set_amount_save);
		cancelButton = (Button) findViewById(R.id.set_amount_cancel);
		saveAndNextButton = (Button) findViewById(R.id.set_amount_save_next_button);
		calcButton = (ImageButton) findViewById(R.id.set_amount_calculator);
		transferAccountButton = (Button) findViewById(R.id.set_amount_transfer_account);
		transferText = (TextView) findViewById(R.id.set_amount_transfer_account_text);
		repeatingTypeButton = (Button) findViewById(R.id.set_amount_repeating_type);
		repeatingEndTimeButton = (Button) findViewById(R.id.set_amount_repeating_end_date);
		repeatingLayout = (LinearLayout) findViewById(R.id.set_amount_repeating_layout);
		repeatingSecondLayout = (LinearLayout) findViewById(R.id.set_amount_repeating_second_layout);
		repeatingSetButton = (Button) findViewById(R.id.set_amount_repeating_occurences_set);
		repeatingPlusButton = (Button) findViewById(R.id.set_amount_repeating_plus);
		repeatingMinusButton = (Button) findViewById(R.id.set_amount_repeating_minus);
		repeatingOccurences = (TextView) findViewById(R.id.set_amount_repeating_occurences);
	}

	private void fillForm() {
		if (actualPayment.getAccount() == null) {
			accountButton.setText(R.string.menu_account_new);
		} else {
			accountButton.setText(actualPayment.getAccount().getName());
		}

		if (actualPayment.getSubcategory() == null) {
			categoryButton.setText(R.string.menu_subcategory_new);
		} else {
			categoryButton.setText(actualPayment.getSubcategory().getFullName());
		}

		dateButton.setText(actualPayment.getDateString(getResources()));
		timeButton.setText(actualPayment.getTimeString(getResources()));
		typeButton.setText(actualPayment.getTypeString(getResources()));

		if (actualPayment.getType() == Payment.TYPE_TRANSFER_TO) {
			accountText.setText(R.string.type_transfer_to);
			transferText.setText(R.string.type_transfer_from);
		} else if (actualPayment.getType() == Payment.TYPE_TRANSFER_FROM) {
			accountText.setText(R.string.type_transfer_from);
			transferText.setText(R.string.type_transfer_to);
		} else {
			accountText.setText(R.string.select_account);
		}

		currencyBeforeText.setText(mPreferenceSettings.getString(getString(R.string.key_currency_before), getString(R.string.currency_before)));
		currencyAfterText.setText(mPreferenceSettings.getString(getString(R.string.key_currency_after), getString(R.string.currency_after)));

		if (actualPayment.getType() == Payment.TYPE_TRANSFER_FROM || actualPayment.getType() == Payment.TYPE_TRANSFER_TO) {
			transferText.setVisibility(View.VISIBLE);
			transferAccountButton.setVisibility(View.VISIBLE);
			categoryText.setVisibility(View.GONE);
			categoryButton.setVisibility(View.GONE);
		} else {
			transferText.setVisibility(View.GONE);
			transferAccountButton.setVisibility(View.GONE);
			categoryText.setVisibility(View.VISIBLE);
			categoryButton.setVisibility(View.VISIBLE);
		}

		if (actualPayment.getType() == Payment.TYPE_DEPOSIT || actualPayment.getType() == Payment.TYPE_TRANSFER_TO) {
			currencyBeforeText.setTextColor(resource.getColor(R.color.deposit));
			currencyAfterText.setTextColor(resource.getColor(R.color.deposit));
			amountText.setTextColor(resource.getColor(R.color.deposit));
		} else if (actualPayment.getType() == Payment.TYPE_WITHDRAW || actualPayment.getType() == Payment.TYPE_TRANSFER_FROM) {
			currencyBeforeText.setTextColor(resource.getColor(R.color.withdraw));
			currencyAfterText.setTextColor(resource.getColor(R.color.withdraw));
			amountText.setTextColor(resource.getColor(R.color.withdraw));
		} else if (actualPayment.getType() == Payment.TYPE_REMAINDER) {
			currencyBeforeText.setTextColor(resource.getColor(R.color.remainder));
			currencyAfterText.setTextColor(resource.getColor(R.color.remainder));
			amountText.setTextColor(resource.getColor(R.color.remainder));
		}

		if (actualPayment.getTransferAccount() == null) {
			transferAccountButton.setText(R.string.select_account);
		} else {
			transferAccountButton.setText(actualPayment.getTransferAccount().getName());
		}

		if (editRepeating == REPEATING_TYPE_NO_REPEATING) {
			// if edit payment of repeating
			repeatingTypeButton.setText(R.string.part_of_repeating);
			repeatingTypeButton.setEnabled(false);
			repeatingLayout.setVisibility(View.GONE);
			if (repeatingSecondLayout != null) {
				repeatingSecondLayout.setVisibility(View.GONE);
			}
		} else {
			repeatingTypeButton.setText(actualPayment.getRepeating().getTypeString(getResources()));
			if (actualPayment.getRepeating().getType() == Repeating.TYPE_NONE) {
				repeatingLayout.setVisibility(View.GONE);
				if (repeatingSecondLayout != null) {
					repeatingSecondLayout.setVisibility(View.GONE);
				}
			} else {
				repeatingLayout.setVisibility(View.VISIBLE);
				if (repeatingSecondLayout != null) {
					repeatingSecondLayout.setVisibility(View.VISIBLE);
				}
			}
		}

		repeatingOccurences.setText(String.valueOf(actualPayment.getRepeating().getOccurrences()));
		repeatingEndTimeButton.setText(actualPayment.getRepeating().getEndDateString(getResources()));
	}

	/**
	 * compute and set amount
	 */
	private boolean fillPayment() {
		if (amountText.getText().length() == 0) {
			Toast.makeText(amountText.getContext(), R.string.warning_amount, Toast.LENGTH_LONG).show();
			return false;
		}

		float amount;
		try {
			final boolean byOperatorPrecedence = mPreferenceSettings.getBoolean(getString(R.string.key_solving_by_precedence), true);
			amountText.setText(CalculatorSolver.solve(amountText.getText().toString(), byOperatorPrecedence));
			amount = Float.parseFloat(amountText.getText().toString().replace(',', '.'));
		} catch (final Exception e) {
			Toast.makeText(amountText.getContext(), R.string.cannot_compute, Toast.LENGTH_LONG).show();
			return false;
		}

		if (actualPayment.getType() == Payment.TYPE_REMAINDER) {
			actualPayment.setRemainder(amount);
		} else {
			actualPayment.setAmount(amount);
		}

		// set values
		final boolean changeType = mPreferenceSettings.getBoolean(getString(R.string.key_type_change), false);
		actualPayment.normalizeAmount(changeType);
		actualPayment.normalizeDate();
		actualPayment.setDescription(descriptionText.getText().toString());

		// check category and account
		if (!actualPayment.checkValues(this)) {
			return false;
		}
		return true;
	}

	/**
	 * create set payment
	 */
	private boolean savePayment() {
		if (!fillPayment()) {
			return false;
		}

		boolean result = true;
		PaymentList.isChanged = true;

		if (actualPayment.getRepeating().getType() == Repeating.TYPE_NONE || editRepeating == REPEATING_TYPE_NO_REPEATING) {
			if (actualPayment.getType() == Payment.TYPE_REMAINDER) {
				actualPayment.computeRemainder(null, mDbHelper);
				result = result && actualPayment.save(mDbHelper);
			} else {
				result = result && actualPayment.save(mDbHelper);
				actualPayment.updateNextRemainder(mDbHelper);
			}
			// update previous payment remainder
			if (lastPayment != null) {
				if (lastPayment.getType() == Payment.TYPE_REMAINDER) {
					lastPayment.computeRemainder(null, mDbHelper);
				} else {
					lastPayment.updateNextRemainder(mDbHelper);
				}
			}
		} else {
			actualPayment.getRepeating().setActualDate((Calendar) actualPayment.getDate().clone());
			if (!actualPayment.getRepeating().save(mDbHelper)) {
				Toast.makeText(this, String.format(getString(R.string.error_database_error), actualPayment.getName()), Toast.LENGTH_LONG).show();
				return false;
			}

			RepeatingList.loadAll(mDbHelper);
			result = result && actualPayment.getRepeating().updatePayments(actualPayment, mDbHelper);
			PaymentList.updateRepeatingRemainder(actualPayment, lastPayment, mDbHelper);
			mDbHelper.updateEntry(actualPayment.getRepeating());
		}

		if (!result) {
			Toast.makeText(this, String.format(getString(R.string.error_database_error), actualPayment.getName()), Toast.LENGTH_LONG).show();
		} else {
			if (editRepeating == REPEATING_TYPE_REPEATING) {
				Toast.makeText(this, String.format(getString(R.string.repeating_was_changed), actualPayment.getName()), Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(this, String.format(getString(R.string.payment_was_saved), actualPayment.getName()), Toast.LENGTH_LONG).show();
			}
		}
		return result;
	}

	private final OnClickListener typeButtonClickListener = new OnClickListener() {
		public void onClick(View v) {
			if (actualPayment.getType() != Payment.TYPE_WITHDRAW) {
				actualPayment.setType(Payment.TYPE_WITHDRAW);
			} else {
				actualPayment.setType(Payment.TYPE_DEPOSIT);
			}
			fillForm();
		}
	};

	private final OnClickListener typeMoreButtonClickListener = new OnClickListener() {
		public void onClick(View v) {
			showDialog(TYPE_MORE_DIALOG);
		}
	};

	private final OnClickListener saveAndNewListener = new OnClickListener() {
		public void onClick(View v) {
			if (actualPayment.getId() > 0) { // payment is edited
				if (savePayment()) {
					final Intent intent = new Intent(SetAmount.this, MHFinance.class);
					startActivity(intent);
					SetAmount.this.finish();
				}
			} else {
				if (savePayment()) {
					SetAmount.this.finish();
				}
			}
		}
	};

	private final OnClickListener saveAndReportListener = new OnClickListener() {
		public void onClick(View v) {
			final Intent data = new Intent();
			data.putExtra(RETURN_SHOW_REPORT, true);
			if (savePayment()) {
				SetAmount.this.setResult(Activity.RESULT_OK, data);
				SetAmount.this.finish();
			}
		}
	};

	private final OnClickListener cancelListener = new OnClickListener() {
		public void onClick(View v) {
			// Close this Activity
			SetAmount.this.finish();
		}
	};

	private final OnClickListener dateButtonListener = new OnClickListener() {
		public void onClick(View v) {
			showDialog(DATE_PICKER_DIALOG);
		}
	};

	private final OnLongClickListener dateButtonLongClickListener = new OnLongClickListener() {
		public boolean onLongClick(View v) {
			actualPayment.setDateToNow();
			fillForm();
			return true;
		}
	};

	private final OnClickListener timeButtonListener = new OnClickListener() {
		public void onClick(View v) {
			showDialog(TIME_PICKER_DIALOG);
		}
	};

	private final OnLongClickListener timeButtonLongClickListener = new OnLongClickListener() {
		public boolean onLongClick(View v) {
			actualPayment.setTime(0, 0);
			fillForm();
			return true;
		}
	};

	private final OnClickListener accountButtonListener = new OnClickListener() {
		public void onClick(View v) {
			final Intent i = new Intent(SetAmount.this, SelectAccount.class);
			startActivityForResult(i, SELECT_ACCOUNT_ACTIVITY);
		}
	};

	private final OnClickListener transferaccountButtonListener = new OnClickListener() {
		public void onClick(View v) {
			final Intent i = new Intent(SetAmount.this, SelectAccount.class);
			startActivityForResult(i, SELECT_TRANSFER_ACCOUNT_ACTIVITY);
		}
	};

	private final OnClickListener categoryButtonListener = new OnClickListener() {
		public void onClick(View v) {
			final Intent i = new Intent(SetAmount.this, SelectCategory.class);
			i.putExtra(SelectCategory.REQUEST_SELECTED_CATEGORY_ID, actualPayment.getSubcategory().getId());
			startActivityForResult(i, SELECT_CATEGORY_ACTIVITY);
		}
	};

	private final OnClickListener calcButtonListener = new OnClickListener() {
		public void onClick(View v) {
			final Intent i = new Intent(SetAmount.this, CalculatorDialog.class);
			i.putExtra(CalculatorDialog.REQUEST_EXPRESSION, amountText.getText().toString());
			startActivityForResult(i, CALCULATOR_ACTIVITY);
		}
	};

	private final OnClickListener repeaterEndDateButtonListener = new OnClickListener() {
		public void onClick(View v) {
			showDialog(REPEATING_END_DATE_PICKER_DIALOG);
		}
	};

	private final OnClickListener repeaterTypeButtonListener = new OnClickListener() {
		public void onClick(View v) {
			showDialog(REPEATING_TYPE_DIALOG);
		}
	};

	private final OnClickListener repeaterPlusButtonListener = new OnClickListener() {
		public void onClick(View v) {
			actualPayment.getRepeating().addOcurences(1, actualPayment.getDate());
			fillForm();
		}
	};

	private final OnClickListener repeaterMinusButtonListener = new OnClickListener() {
		public void onClick(View v) {
			actualPayment.getRepeating().addOcurences(-1, actualPayment.getDate());
			fillForm();
		}
	};

	private final OnLongClickListener repeaterPlusButtonLongListener = new OnLongClickListener() {
		public boolean onLongClick(View v) {
			actualPayment.getRepeating().addOcurences(10, actualPayment.getDate());
			fillForm();
			return true;
		}
	};

	private final OnLongClickListener repeaterMinusButtonLongListener = new OnLongClickListener() {
		public boolean onLongClick(View v) {
			actualPayment.getRepeating().addOcurences(-10, actualPayment.getDate());
			fillForm();
			return true;
		}
	};

	private final OnClickListener repeaterSetButtonListener = new OnClickListener() {
		public void onClick(View v) {

			if (repeatingOccurences.getText().toString().length() == 0) {
				actualPayment.getRepeating().setOccurrences(0, actualPayment.getDate());
			} else {
				actualPayment.getRepeating().setOccurrences(Integer.parseInt(repeatingOccurences.getText().toString()), actualPayment.getDate());
			}
			fillForm();
		}
	};

	private final android.content.DialogInterface.OnClickListener repeatingTypeSelectButtonListener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			if (actualPayment.getRepeating().isEndDateNotSet()) {
				actualPayment.getRepeating().setEndDate(actualPayment.getYear(), actualPayment.getMonth(), actualPayment.getDay());
			}

			switch (which) {
				case 0:
					actualPayment.getRepeating().setType(Repeating.TYPE_NONE, actualPayment.getDate());
					break;
				case 1:
					actualPayment.getRepeating().setType(Repeating.TYPE_DAILY, actualPayment.getDate());
					break;
				case 2:
					actualPayment.getRepeating().setType(Repeating.TYPE_WEEKLY, actualPayment.getDate());
					break;
				case 3:
					actualPayment.getRepeating().setType(Repeating.TYPE_MONTHLY, actualPayment.getDate());
					break;
				case 4:
					actualPayment.getRepeating().setType(Repeating.TYPE_MONTHLY_DAY, actualPayment.getDate());
					break;
				case 5:
					actualPayment.getRepeating().setType(Repeating.TYPE_QUARTER_YEARLY, actualPayment.getDate());
					break;
				case 6:
					actualPayment.getRepeating().setType(Repeating.TYPE_YEARLY, actualPayment.getDate());
					break;
			}

			fillForm();
		}
	};

	private final android.content.DialogInterface.OnClickListener remainderInfoClickListener = new android.content.DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			final SharedPreferences.Editor editor = mPreferenceSettings.edit();
			editor.putBoolean(getString(R.string.key_remainder_info), false);

			editor.commit();
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
			case CALCULATOR_ACTIVITY:
				if (resultCode == RESULT_OK) {
					amountText.setText(data.getStringExtra(CalculatorDialog.RETURN_CALCULATOR_RESULT));
				}
				break;

			case SELECT_ACCOUNT_ACTIVITY:
				if (resultCode == RESULT_OK) {
					final int index = data.getIntExtra(SelectAccount.RETURN_ACCOUNT_POSITION, -1);
					if (index >= 0) {
						actualPayment.setAccount(AccountsList.getAccount(index));
					}
				} else {
					if (actualPayment.getAccount() != null) {
						actualPayment.setAccountById(actualPayment.getAccount().getId());
					}
				}
				fillForm();
				break;

			case SELECT_TRANSFER_ACCOUNT_ACTIVITY:
				if (resultCode == RESULT_OK) {
					final int index = data.getIntExtra(SelectAccount.RETURN_ACCOUNT_POSITION, -1);
					if (index >= 0) {
						actualPayment.setTransferAccount(AccountsList.getAccount(index));
					}
				} else {
					if (actualPayment.getTransferAccount() != null) {
						actualPayment.setTransferAccountId(actualPayment.getTransferAccount().getId());
					}
				}
				fillForm();
				break;

			case SELECT_CATEGORY_ACTIVITY:
				if (resultCode == RESULT_OK) {
					final int mainPosition = data.getIntExtra(SelectCategory.RETURN_CATEGORY_POSITION, -1);
					final int childPosition = data.getIntExtra(SelectCategory.RETURN_SUBCATEGORY_POSITION, -1);
					if (mainPosition >= 0 && childPosition >= 0) {
						actualPayment.setSubcategory(CategoryList.getSubcategory(mainPosition, childPosition));
					}
				} else {
					if (actualPayment.getSubcategory() != null) {
						actualPayment.setSubcategoryById(actualPayment.getSubcategory().getId());
					}
				}
				fillForm();
				break;
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(SetAmount.REQUEST_REPEATING, editRepeating);
		actualPayment.fillBundle(outState);
		actualPayment.getRepeating().fillBundle(outState);
	}
}
